package us.codecraft.webmagic.samples;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

/**
 * @author 410775541@qq.com <br>
 * @since 0.5.1
 */
public class Page0818TuanProcessor implements PageProcessor {

    private Site site = Site.me().setCycleRetryTimes(5).setRetryTimes(5).setSleepTime(500).setTimeOut(3 * 60 * 1000)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0")
            .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
            .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
            .setCharset("gb2312");
//            .setCharset("UTF-8");

    private static int pageNo = 1;


    private static final String URL_PREFIX = "http://wx.0818tuan.com";
    private static final String URL_FORMAT = URL_PREFIX + "/list-1-%S.html";

    @Override
    public void process(Page page) {
        List<Selectable> nodes = page.getHtml().xpath("//div[@id='redtag']//a[@class='list-group-item']").nodes();

        nodes.forEach(n -> {
            String title = n.xpath("//a/@title").toString();

            if (title.contains("12306") || title.contains("火车票")) {
                String href = n.xpath("//a/@href").toString();
                String msg = title + "  " + URL_PREFIX + href;
                System.out.println(msg);
            }
        });

        if (pageNo < 1000) {
            page.addTargetRequest(String.format(URL_FORMAT, pageNo));
            pageNo++;
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new Page0818TuanProcessor()).
                addUrl("http://wx.0818tuan.com/list-1-0.html").
                addPipeline(new FilePipeline("D:\\webmagic\\")).
                thread(1).
                run();
    }
}
